﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ApplicationShell
{
    /// <summary>
    /// Interaction logic for ApplicationLauncher.xaml
    /// </summary>
    public partial class ApplicationLauncher : UserControl
    {
        public class LaunghApplicationEventArgs : EventArgs
        {
            public string Path { get; set; }
            public string Arguments { get; set; }

            public LaunghApplicationEventArgs( string path, string arguments )
            {
                Path = path;
                Arguments = arguments;
            }
        }

        public event EventHandler<LaunghApplicationEventArgs> OnLaunchApplication;

        private Cursor _restoreCursor;
        private string _path;
        private string _args;

        public ApplicationLauncher(tblApplication application)
        {
            InitializeComponent();

            // Set the application name
            lblApplication.Content = application.Name;

            ToolTip = application.Description;

            // Get a bitmap for the application
            try
            {
                BitmapSource bms;
                if (application.IconPath == null)
                    bms = IconHandler.IconHandler.BitmapSource(application.Path, IconHandler.IconSize.Large, 0);
                else
                {
                    IconBitmapDecoder decoder = new IconBitmapDecoder(new System.Uri(application.IconPath, UriKind.RelativeOrAbsolute),
                        BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

                    bms = decoder.Frames[0];
                }
                imgApplication.Source = bms;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

            _path = application.Path;
            _args = application.Arguments;
        }

        private void UserControl_MouseEnter(object sender, MouseEventArgs e)
        {
            _restoreCursor = this.Cursor;
            this.Cursor = Cursors.Hand;
        }

        private void UserControl_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = _restoreCursor;
        }

        private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            OnLaunchApplication(this, new LaunghApplicationEventArgs(_path, _args));
        }
    }
}
